package com.example.fw;

import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.example.tests.ContactData;
import com.example.tests.ContactFromFormData;
import com.example.utils.SortedListOf;

public class ContactHelper extends WebDriverHelperBase {
	
	public static boolean CREATION = true;
	public static boolean MODIFICATION = false;

	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
		
	private SortedListOf<ContactData> cachedContacts;
	
	public SortedListOf<ContactData> getContactsFromCache() {
		if (cachedContacts == null) {
			rebuildCache();
		}
		return cachedContacts;
	}
	// Empty bDay value's saved as "0" into BD. 
	// For correct comparing of Contact data from BD and UI it's necessary to set bDay value to "-" if it's "0"
	private void rebuildCache() {
		cachedContacts = manager.getHibernateHelper().listContacts();
		for (ContactData contact : cachedContacts ) {
			if (contact.getbDay().equals("0")){
				contact.withBDay("-");
			}
		}
	}

	public SortedListOf<ContactData> getContacts() {
		    SortedListOf<ContactData> contacts = new SortedListOf<ContactData>();
            List<WebElement> rows = driver.findElements(By.xpath("//tr[@name='entry']"));
            for (WebElement row : rows) {
            	List<WebElement> cells = row.findElements(By.tagName("td"));
    			String lastName = cells.get(1).getText(); 
    			String firstName = cells.get(2).getText(); 
    			String email1 = cells.get(3).getText(); 
    			String homePhone = cells.get(4).getText(); 
    			ContactData contact = new ContactData()
    				.withLastName(lastName)
    				.withFirstName(firstName)
    				.withEmail1(email1)
    				.withHomePhone(homePhone);
                    contacts.add(contact);
            }
            return contacts;
    }


	public SortedListOf<ContactData> getContactsFromModel() {
		return manager.getModel().getContacts();
	}

	public ContactHelper createContact(ContactData contact) {
		manager.navigateTo().mainPage();
    	goToAddContactPage();
    	fillContactData(contact, CREATION);
    	submitContactCreation();
    	returnToHomePage();
    	manager.getModel().addContact(contact);
    	// It is not needed to rebuildCache here due to cachedContacts = null during submitContactCreation()
    	//rebuildCache();
    	return this;
	}
	
	public ContactFromFormData modifyContact(ContactData contact, int index) {
		manager.navigateTo().mainPage();
		initContactModification(index);
		// get Contact data from Edit Contact Form
		ContactFromFormData contactFromForm = getContactDataFromForm();
		
		fillContactData(contact, MODIFICATION);
		submitContactModification();
		returnToHomePage();
		// It is not needed to rebuildCache here due to cachedContacts = null during submitContactModification()
		//rebuildCache();
		manager.getModel().removeContact(index).addContact(contact); // it's important- to remove first, then add
		return contactFromForm;
	}

	private ContactFromFormData getContactDataFromForm() {
		String firstname = getInputFieldVal(By.name("firstname"));
		String lastname = getInputFieldVal(By.name("lastname"));
		String address = getTextareaFieldVal(By.name("address"));
		String homePhone = getInputFieldVal(By.name("home"));
		String mobilePhone = getInputFieldVal(By.name("mobile"));
		String workPhone = getInputFieldVal(By.name("work"));
		String email1 = getInputFieldVal(By.name("email"));
		String email2 = getInputFieldVal(By.name("email2"));
		String bDay = getSelectFieldVal(By.xpath("//select[@name='bday']/option[@selected='selected']"));
		String bMonth = getSelectFieldVal(By.xpath("//select[@name='bmonth']/option[@selected='selected']"));
		String bYear = getInputFieldVal(By.name("byear"));
		String address2 = getTextareaFieldVal(By.name("address2"));
		String phone2 = getInputFieldVal(By.name("phone2"));
		ContactFromFormData contact = new ContactFromFormData()
			.withFirstName(firstname) 
			.withLastName(lastname) 
			.withAddress(address) 
			.withHomePhone(homePhone) 
			.withMobilePhone(mobilePhone) 
			.withWorkPhone(workPhone) 
			.withEmail1(email1) 
			.withEmail2(email2) 
			.withBDay(bDay) 
			.withBMonth(bMonth) 
			.withBYear(bYear) 
			.withAddress2(address2) 
			.withPhone2(phone2);
		return contact;
	}

	public ContactHelper deleteContact(int index) {
		  manager.navigateTo().mainPage();
		  initContactModification(index);
		  submitContactRemoving();
		  returnToHomePage();
		  // It is not needed to rebuildCache here due to cachedContacts = null during submitContactRemoving()
		  //rebuildCache();
		  manager.getModel().removeContact(index);
		  return this;
	}
	
	//---------------------------------------------------------------
	
	public ContactHelper goToAddContactPage() {
		click(By.linkText("add new"));
		return this;
	}
	
	public ContactHelper fillContactData(ContactData contact, boolean formType) {
		type(By.name("firstname"), contact.getFirstName());
		type(By.name("lastname"), contact.getLastName());
		type(By.name("address"), contact.getAddress());
		type(By.name("home"), contact.getHomePhone());
		type(By.name("mobile"), contact.getMobilePhone());
		type(By.name("work"), contact.getWorkPhone());
		type(By.name("email"), contact.getEmail1());
		type(By.name("email2"), contact.getEmail2());		
	    selectByText(By.name("bday"), contact.getbDay());
		selectByText(By.name("bmonth"), contact.getbMonth());
		type(By.name("byear"), contact.getbYear());
		if (formType == true) {
			selectByText(By.name("new_group"), contact.getContactGroup());
		}
	    type(By.name("address2"), contact.getAddress2());	
	    type(By.name("phone2"), contact.getPhone2());	
	    return this;
	}
	
	public ContactHelper submitContactCreation() {
		click(By.name("submit"));
		cachedContacts = null;
		return this;
	}

	public ContactHelper returnToHomePage() {
		click(By.linkText("home page"));
		return this;
	}
	

	public ContactHelper initContactModification(int index) {
		index = index+1;
		click(By.xpath("(//img[@title='Edit'])[" + index + "]"));
		return this;
	}

	public ContactHelper submitContactRemoving() {
		click(By.xpath("(//input[@value='Delete'])"));
		cachedContacts = null;
		return this;
	}

	public ContactHelper submitContactModification() {
		click(By.xpath("(//input[@value='Update'])"));
		cachedContacts = null;
		return this;
	}

	public List <String> getGroupsListFromAddContactPage() {
		List<String> groups = new ArrayList<String>();
		List<WebElement> cells = driver.findElements(By.xpath("//select[@name='new_group']/option"));
		for (WebElement cell : cells) {
			String group = cell.getText();
			groups.add(group);
		}
		return groups;
	}

	public List<String> getBdayListFromAddContactPage() {
		List<String> days = new ArrayList<String>();
		List<WebElement> cells = driver.findElements(By.xpath("//select[@name='bday']/option"));
		for (WebElement cell : cells) {
			String day = cell.getText();
			days.add(day);
		}
		return days;
	}

	public List<String> getBmonthListFromAddContactPage() {
		List<String> months = new ArrayList<String>();
		List<WebElement> cells = driver.findElements(By.xpath("//select[@name='bmonth']/option"));
		for (WebElement cell : cells) {
			String month = cell.getText();
			months.add(month);
		}
		return months;
	}

}
